<?php

namespace app\admin\controller\package;

use service\JsonService;
use app\common\model as M;

/**
 * 分类模块
 */
class Package extends \app\admin\controller\AuthController
{
	public $model = '\app\common\model\Package';

    use \traits\ShotcutControllerTrait;

    public function _save ($data)
    {
        if ( isset($data['cover']) && is_array($data['cover']) ) {
            $data['cover'] = json_encode($data['cover'] , JSON_UNESCAPED_UNICODE);
        }

        if ( isset($data['expire_type']) && $data['expire_type'] == 2 ) {
            if ( isset($data['expire_time']) && $data['expire_time'] ) {
                $data['expire_time'] = $data['expire_time'] . ' 23:59:59';
            }
        }

        if ( isset($data['items']) ) {
            if ( $data['valid_type'] == 1 ) {
                $data['valid_nums'] = 0;
                foreach ( $data['items'] as $item ) {
                    $data['valid_nums'] += $item['valid_nums'];
                }
            }

            if ( $data['valid_type'] == 2 ) {
                foreach ( $data['items'] as &$item ) {
                    $item['valid_nums'] = $data['valid_nums'];
                }
            }
        }
        return $data;
    }

     /**
     * [可退套餐列表]
     * @Author   FW
     * @DateTime 2021-08-12
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     * @return   [type]               [description]
     */
    public function refundable_list ($uid)
    {
        $page  = $this->request->get('page' , 1);
        $limit = $this->request->get('limit' , 10);

        $data  = [];
        $count = 0;

        $count = M\BoughtPackage::alias('b')
        ->where(['b.status' => M\Order::STATUS_VALID, 'b.uid' => $uid])->count();
        if ( $count == 0 ) {
            return JsonService::successlayui($count , $data);
        }

        $data = M\BoughtPackage::alias('b')
        ->field('b.id as bought_id,b.bought_price,b.used_nums,p.name as pck_name,p.valid_type,p.valid_nums')
        ->join('__PACKAGE__ p' , 'b.pck_id = p.id','left')
        ->where(['b.status' => M\Order::STATUS_VALID , 'b.uid' => $uid])
        ->page($page)
        ->limit($limit)
        ->select();

        if ( !empty($data) ) {
            $data = $data->toArray();

            foreach ( $data as &$bought ) {
                $bought['valid_type_display'] = $this->model::$valid_type[$bought['valid_type']] ?? '-';
                ## 不限次数
                if ( $bought['valid_type'] == 3 ) {
                    $bought['left_nums']  = '-';
                    $bought['total_nums'] = '-';
                } else {
                    $bought['left_nums']  = $bought['valid_nums'] - $bought['used_nums'];
                    $bought['total_nums'] = $bought['valid_nums'];
                }
                ## 追加退款金额字段
                $bought['refund_amt']  = $bought['bought_price'];
                $bought['is_selected'] = false;
            }
        }

        return JsonService::successlayui($count , $data);
    }

    /**
     * 退套餐
     * @Author   FW
     * @DateTime 2021-08-12
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function returnpackage ()
    {
        $post    = $this->request->post();
        $uid     = $post['uid'] ?? 0;
        $remark  = $post['remark'] ?? '用户退套餐';
        $packages= $post['packages'] ?? [];

        sleep(2);

        if ( empty($packages) || !is_array($packages) ) {
            return JsonService::fail('至少选择一个套餐');
        }

        ## 用户检查
        $user = M\User::field('uid,org_id,school_id')->where(['uid' => $uid , 'status' => 1])->find();
        if ( !$user ) {
            return JsonService::fail('用户不存在或已被禁用');
        }

        $refund_amt = 0;
        $order_pcks = [];
        foreach ( $packages as $package ) {
            if ( !isset($package['bought_id']) || !isset($package['refund_amt']) ) continue;

            $refund_amt  += $package['refund_amt'];

            $bought_package = M\BoughtPackage::alias('b')
            ->field('p.name as pck_name,b.id as bought_id,b.pck_id')
            ->join('__PACKAGE__ p' , 'p.id = b.pck_id' , 'left')
            ->where(['b.id' => $package['bought_id'] , 'b.status' => 1 , 'b.uid' => $uid])
            ->find();
            if ( empty($bought_package) ) continue;

            $order_pcks[] = [
                'order_id'  =>    0,
                'pck_id'    =>    $bought_package->pck_id,
                'rel_name'  =>    $bought_package->pck_name,
                'bought_id' =>    $bought_package->bought_id,
                'price'     =>    0,
                'amt'       =>    $package['refund_amt'],
                'qty'       =>    1
            ];
        }
        if ( empty($order_pcks) ) {
            return JsonService::fail('待退套餐为空或校验失败，请检查');
        }

        $this->model::beginTrans();
        try {
            $org_id    = $this->model::getBelongOrganId();
            $school_id = $this->model::getBelongSchoolId();

            ## 创建订单
            $order['orgn_amt']       = -$refund_amt;
            $order['disc_amt']       = 0;
            $order['order_amt']      = $order['orgn_amt'] - $order['disc_amt'];
            $order['uid']            = $user->uid;
            $order['pub_aid']        = $this->adminId;
            $order['refund_type']    = 2;
            $order['platform']       = M\Order::PTF_BACKEND;
            $order['remark']         = $remark;
            $order['org_id']         = ( $org_id > 0 ) ? $org_id : $user->org_id;
            $order['school_id']      = ( $school_id > 0 ) ? $school_id : $user->school_id;

            ## 记录待退套餐详情
            $order['refund_packages']= $order_pcks;
            $order_id = \app\common\model\order\UserRefund::create_order($order);
            if ( !$order_id ) {
                return JsonService::fail('创建订单失败【0981】');
            }
            $order['order_id']       = $order_id;

            $this->model::commitTrans();
            return JsonService::successful('退套餐订单创建成功，请确认' , $order);
        } catch ( \Exception $e ) {
            $this->model::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return JsonService::fail('操作失败');
    }

     /**
     * 退套餐确认
     * @method POST
     * @return [type] [description]
     */
    public function returnconfirm ()
    {
        $post = $this->request->post();

        $order_id = $post['order_id'] ?? 0;

        if ( !$order_id ) return JsonService::fail('订单ID不能为空');

        $order = M\Order::field('order_no,order_type,refund_type')->where('id' , $order_id)->find();
        if ( !$order ) return JsonService::fail('订单不存在');

        if ( $order->order_type != M\Order::ORDER_TYPE_REFUND || $order->refund_type != 2 ) {
            return JsonService::fail('操作失败,请稍候再试[0082]');
        }

        $res = M\Order::paySuccess($order->order_no , 'IO' . date('YmdHis') . mt_rand(1000,9999) , 0);
        if ( $res === true ) return JsonService::successful('操作成功');

        if ( is_string($res) ) return JsonService::fail($res);

        return JsonService::fail('操作失败,请稍候再试');
    }

    /**
     * 删除内容项
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete_item ($id)
    {
        if ( $id > 0 ) {
            $pck = M\PackageItems::where('id' , $id)->field('valid_nums,pck_id')->find();

            if ( $pck !== false ) {
                ## 减少套餐可用数量
                M\Package::where('id' , $pck->pck_id)->setDec('valid_nums' , $pck->valid_nums);

                $pck->delete();

                return JsonService::successful('删除成功');
            }
        }

        return JsonService::fail('删除失败,请稍候再试');
    }
}